package com.atguigu.flink.chapter2;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;


/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2020/12/18 10:34
 * 有界流
 */
public class Flink03_WC_BoundStream {
    public static void main(String[] args) throws Exception {
        // 1. 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2. 从文件中获取一个流
        DataStreamSource<String> sourceStream = env.readTextFile("input");

        // 3. 做各种转换
        SingleOutputStreamOperator<Tuple2<String, Long>> wordAndOne = sourceStream.flatMap((String value, Collector<Tuple2<String, Long>> out) -> {
            String[] split = value.split(" ");
            for (String word : split) {
                out.collect(Tuple2.of(word, 1L));
            }
        }).returns(Types.TUPLE(Types.STRING, Types.LONG));

        KeyedStream<Tuple2<String, Long>, String> wordAndOneKeyed = wordAndOne.keyBy(value -> value.f0);

        SingleOutputStreamOperator<Tuple2<String, Long>> result = wordAndOneKeyed.sum(1);
        result.print("sum...");


        // 4. 启动执行环境
        env.execute();
    }
}
